package main

import (
	"go_practice/structs"
)

type TreeNode = structs.TreeNode

// 二叉树的层平均值

func averageOfLevels(root *TreeNode) []float64 {
	if root == nil {
		return []float64{}
	}
	var res []float64
	stk := []*TreeNode{root}
	for len(stk) > 0 {
		curLen := len(stk)
		curLevelSum := 0
		for i := 0; i < curLen; i++ {
			curNode := stk[0]
			stk = stk[1:]
			curLevelSum += curNode.Val
			if curNode.Left != nil {
				stk = append(stk, curNode.Left)
			}
			if curNode.Right != nil {
				stk = append(stk, curNode.Right)
			}
		}
		res = append(res, float64(curLevelSum)/float64(curLen))
	}
	return res
}
